package chan.project.smartlaweveryman.controller.inner;

import chan.project.smartlawcommon.common.ErrorCode;
import chan.project.smartlawcommon.constant.TokenConstant;
import chan.project.smartlawcommon.exception.BusinessException;


import chan.project.smartlaweveryman.service.UserInfoService;
import chan.project.smartlaweveryman.service.UserRoleService;
import chan.project.smartlawmodel.entity.UserInfo;
import chan.project.smartlawmodel.entity.UserRole;
import chan.project.smartlawmodel.enums.UserRoleEnum;
import chan.project.smartlawmodel.vo.UserInfoVO;
import chan.project.smartlawservice.userService.UserFeignClient;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import io.jsonwebtoken.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/user/inner")
public class UserControllerInner implements UserFeignClient {

    @Resource
    private UserInfoService userService;

    @Resource
    private UserRoleService userRoleService;

    @Override
    @GetMapping("/getById")
    public UserInfo getById(@RequestParam("userId") Long userId) {
        return userService.getById(userId);
    }

    @Override
    @GetMapping("/getIds")
    public List<UserInfo> listByIds(@RequestParam("idList") Collection<Long> idList) {
        return userService.listByIds(idList);
    }
    @Override
    @GetMapping("/getLoginUser")
    public UserInfoVO getLoginUser(){
        //获取token
        String userId = (String) StpUtil.getLoginId();
        String role = (String) StpUtil.getExtra("role");
        List<UserRole> userRole = userRoleService.getUserRoleByUserId(userId, role);
        if(CollectionUtils.isEmpty(userRole)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"当前用户不存在或者无权限");
        }
        if(ObjectUtil.isEmpty(userId)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户token异常");
        }
        UserInfo byId = this.getById(Long.valueOf(userId));
        if(ObjectUtil.isEmpty(byId)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"当前用户不存在");
        }
        UserInfoVO userInfoVO = UserInfoVO.objToVo(byId);
        userInfoVO.setUserRole(role);
        return userInfoVO;
    }
}
